﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using ProjectEuler.Linq;

namespace ProjectEuler.Problems
{
    [EulerProblem(50, 997651)]
    [Description("Which prime, below one-million, can be written as the sum of the most consecutive primes?")]
    internal sealed class Problem050 : EulerProblem
    {
        private const Int32 Limit = 1000000;

        public override Object Solve()
        {
            var sieve = new SieveOfEratosthenes(Limit);
            var primes = sieve.ToArray();

            var maxCount = 0;
            var maxPrime = 0;

            var start = 0;
            var count = 0;

            var sum = 0;

            while ((start < primes.Length) && (primes[start] < (Limit / 2)))
            {
                while (sum < Limit)
                {
                    sum += primes[start + count];
                    count++;

                    if ((sum < Limit) && (count > maxCount) && sieve.IsPrime(sum))
                    {
                        maxCount = count;
                        maxPrime = sum;
                    }
                }

                start++;
                count = 1;
                sum = primes[start];
            }

            return maxPrime;
        }
    }
}
